package com.jvyou.app.ds.controller;


import com.jvyou.app.common.domain.entity.SysFile;
import com.jvyou.app.common.domain.model.Result;
import com.jvyou.app.common.enums.HttpCodeEnum;
import com.jvyou.app.ds.service.SysFileService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件表(SysFile)表控制层
 *
 * @author 橘柚
 * @since 2025-03-07 11:00:41
 */
@RestController
@RequestMapping("/file")
public class SysFileController {

    @Resource
    private SysFileService sysFileService;

    /**
     * 统一文件上传服务
     *
     * @param file 原始文件
     * @return 文件信息
     */
    @PostMapping("/upload")
    public Result<SysFile> upload(MultipartFile file) {
        return Result.success(sysFileService.upload(file));
    }

    @GetMapping("/download/{id}")
    public void download(@PathVariable Long id, HttpServletResponse response) {
        sysFileService.download(id, response);
    }


    @GetMapping("/downloadByPath")
    public void downloadByPath(@RequestParam String path, HttpServletResponse response) {
        sysFileService.downloadByPath(path, response);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/{id}")
    public Result<SysFile> selectOne(@PathVariable Long id) {
        return Result.success(sysFileService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param sysFile 实体对象
     * @return 新增结果
     */
    @PostMapping
    public Result<SysFile> insert(@RequestBody SysFile sysFile) {
        boolean success = sysFileService.save(sysFile);
        return success ? Result.success(sysFile) : Result.error(HttpCodeEnum.ADD_FAIL);
    }

    /**
     * 修改数据
     *
     * @param sysFile 实体对象
     * @return 修改结果
     */
    @PutMapping("/updateById")
    public Result<SysFile> updateById(@RequestBody SysFile sysFile) {
        boolean success = sysFileService.updateById(sysFile);
        return success ? Result.success(sysFile) : Result.error(HttpCodeEnum.UPDATE_FAIL);
    }


    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        boolean success = sysFileService.removeById(id);
        return success ? Result.success(true) : Result.error(HttpCodeEnum.DELETE_FAIL);
    }

}

